//
//  GetBTInfoPlugin.m
//  PCDBankSix
//
//  Created by APPLE on 2023/8/22.
//

#import "GetBTInfoPlugin.h"
#import "PCDBluetoothManager.h"
#import "YTUkeyEnterpriseModel.h"
#import "PCDUkeyAlertView.h"
#import "YTBluetoothAuthHandle.h"
#import "YTUKeySNAlertView.h"
#import "PCDFTUkeyManager.h"
#import "IBankDevice.h"

@interface GetBTInfoPlugin ()<disconnectedDelegate>

/// PIN码弹窗
@property (strong ,nonatomic)PCDUkeyAlertView *ukAlertView;
@property (nonatomic,copy) NSString * PIN;
@property (nonatomic,copy) NSString * strCallback;
@property (nonatomic,copy) NSString * failCallback;
@property (nonatomic,copy) NSString * ukeyCodeType;
@property (nonatomic,copy) NSString * SN;
@property (nonatomic,copy) NSString * businessText;
@property (nonatomic,strong) PCDBankWebViewController * vc;

@end

@implementation GetBTInfoPlugin


- (void)handler:(id)data andContext:(PCDContext *)context ResponseCallback:(WVJBResponseCallback )responseCallback{
    
    NSDictionary *dictData = (NSDictionary *)data;
    self.vc = context.viewController;
    self.strCallback = dictData[@"success"];
    self.failCallback = dictData[@"fail"];
    self.ukeyCodeType = dictData[@"ukeyCodeType"];
    self.SN = dictData[@"SN"];
    self.businessText = dictData[@"businessText"];//交易信息
    
    Weakify(self);
    //获取蓝牙权限
    [YTBluetoothAuthHandle.sharedInstance requestBluetoothRequest:^(BOOL granted, CBManagerState status) {
       if (granted) {
           [wself connectUKey];
       }else {
           evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":@""} JSONRepresentation]);
           if (status == CBManagerStateUnauthorized) {
               [PCDCommonTools showBluetoothAuthAlert];
           }
       }
   }];
}

- (void)connectUKey {
    Weakify(self);
    if ([self.ukeyCodeType integerValue] == 1) {
        //飞天
        [PCDFTUkeyManager.sharedInstance addKeyEventsListener];
        PCDFTUkeyManager.sharedInstance.delegate = self;
        [self.vc.view showHBWaitWithTitle:@"蓝牙key连接中..." isFullScreen:YES];
        [PCDFTUkeyManager.sharedInstance ft_connectUKeyWithSN:wself.SN connectBlock:^(BOOL result, id  _Nonnull enterpriseInfo) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [wself.vc.view showHBWait:NO isFullScreen:YES];
                if (result) {/// 连接成功
                    YTBluetoothAuthHandle.sharedInstance.ukeyType = YTUkeyConnectType_FT;
                    //校验蓝牙key密码
                    [wself showPINTextFieldAlert:^(NSString *PINCode) {
                        if ([PINCode isEqualToString:@"取消"]) {
                            evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{} JSONRepresentation]);
                            return;
                        }
                        [wself.vc.view showHBWait:YES isFullScreen:YES];
                        dispatch_async(dispatch_get_global_queue(0, 0), ^{
                            [PCDFTUkeyManager.sharedInstance ft_verifyPIN:PINCode complateBlock:^(BOOL result, NSString * _Nonnull error) {
                                if (result) {
                                    [PCDFTUkeyManager.sharedInstance ft_signBluetoothKeyInfo:wself.businessText pin:PINCode completeBlock:^(BOOL result, NSString * _Nonnull signInfo) {
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            [wself.vc.view showHBWait:NO isFullScreen:YES];
                                            if (result) {
                                                evaluateJavaScriptOnMainThread(wself, wself.strCallback, [@{@"SignRet":signInfo} JSONRepresentation]);
                                            }else {
                                                evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":@"蓝牙key签名失败"} JSONRepresentation]);
                                            }
                                        });
                                    }];
                                }else {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [wself.vc.view showHBWait:NO isFullScreen:YES];
                                        evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":error} JSONRepresentation]);
                                    });
                                }
                            }];
                        });
                       
                    }];
                } else {/// 连接失败
                    evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":enterpriseInfo} JSONRepresentation]);
                }
            });
        }];
    }else if ([self.ukeyCodeType integerValue] == 2) {
        //文鼎
        [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(wd_didDisconnectUkey:) name:ESIBankDeviceDidDisconnect object:nil];
        [self.vc.view showHBWaitWithTitle:@"蓝牙key连接中..." isFullScreen:YES];
        [PCDBluetoothManager.shareManager connectUKeyWithSN:wself.SN connectBlock:^(BOOL result, id  _Nonnull model) {
            [wself.vc.view showHBWait:NO isFullScreen:YES];
            if (result) {///连接成功
                YTBluetoothAuthHandle.sharedInstance.ukeyType = YTUkeyConnectType_WD;
                
                //判断是否为默认密码，是则需要强制改密
                [PCDBluetoothManager.shareManager isDeviceDefaultPINWithCompleteBlock:^(BOOL result, NSString * _Nonnull errorString) {
                    if (result) {
                        [PCDBluetoothManager.shareManager UIchangePINCodeWithCompleteBlock:^(BOOL result, NSString * _Nonnull errorString) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [PCDUtil toastMessage:errorString];
                                [wself.vc.navigationController popToRootViewControllerAnimated:YES];
                            });
                        }];
                    }else {
                        //校验蓝牙key密码并且签名
                        [PCDBluetoothManager.shareManager UIsignBluetoothKeyInfo:wself.businessText completeBlock:^(BOOL result, NSString * _Nonnull signInfo) {
                            if (result) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    evaluateJavaScriptOnMainThread(wself, wself.strCallback, [@{@"SignRet":signInfo} JSONRepresentation]);
                                });
                            }else {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":@"蓝牙key签名失败"} JSONRepresentation]);
                                });
                            }
                            
                        }];
                    }
                }];
                
            } else {/// 连接失败
                dispatch_async(dispatch_get_main_queue(), ^{
                    evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":model} JSONRepresentation]);
                });
            }
        }];
    }
}


- (void)showPINTextFieldAlert:(void(^)(NSString * PINCode))completeBlock{
    Weakify(self);
    [_ukAlertView removeFromSuperview];
    _ukAlertView = [[PCDUkeyAlertView alloc]init];
    if (YTBluetoothAuthHandle.sharedInstance.ukeyType == YTUkeyConnectType_FT) {
        [_ukAlertView.UkeyView.code1View ft_configKeyboard];
    } else {
        [_ukAlertView.UkeyView.code1View wd_configKeyborad];
    }
    _ukAlertView.UkeyView.returnPINPwd = ^(NSString * _Nonnull code) {
        wself.PIN = code;
        [wself.ukAlertView removeFromSuperview];
        completeBlock(code);
    };
    _ukAlertView.UkeyView.clickCancelBlock = ^{
        [wself.ukAlertView removeFromSuperview];
        completeBlock(@"取消");
    };

    [_ukAlertView show];
}

- (void)wd_didDisconnectUkey:(NSNotification *)noti{
    Weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":@"蓝牙key已经断开连接"} JSONRepresentation]);
    });
}

-(void)FTdisconnectedAction {
    Weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        evaluateJavaScriptOnMainThread(wself, wself.failCallback, [@{@"errCode":@"蓝牙key已经断开连接"} JSONRepresentation]);
    });
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (YTBluetoothAuthHandle.sharedInstance.ukeyType == YTUkeyConnectType_FT) {
        [PCDFTUkeyManager.sharedInstance ft_didDeviceDisconnected:^(BOOL success, NSInteger errorCode) {}];
    } else {
        [PCDBluetoothManager.shareManager didDeviceDisconnected:^(BOOL success, NSString * _Nonnull errorCode) {}];
    }
    [PCDFTUkeyManager.sharedInstance removeKeyEventsListener];
}

@end
